package com.youdianstar.app.ui.pay

import android.app.Dialog
import android.os.Handler
import android.os.Looper
import android.view.View
import android.widget.CheckBox
import android.widget.ImageView
import androidx.recyclerview.widget.LinearLayoutManager
import com.gyf.immersionbar.ImmersionBar
import com.safframework.eventbus.EventBus

import com.youdianstar.app.R
import com.youdianstar.app.BR
import com.youdianstar.app.common.BisType
import com.youdianstar.app.common.base.BaseActivity
import com.youdianstar.app.entity.CardEntity
import com.youdianstar.app.entity.WalletInfo

import com.youdianstar.app.common.ex.setThrottleListener
import com.youdianstar.app.common.network.BaseApiResultObserver
import com.youdianstar.app.common.util.MathUtil
import com.youdianstar.app.adapter.CardBannerAdapter

import com.youdianstar.app.databinding.ActivityWalletBinding
import com.youdianstar.app.entity.CardBanner
import com.youdianstar.app.entity.CardUnbindRes
import com.youdianstar.app.support.paging.ICardEditListener
import com.youdianstar.app.support.paymentActionIntent
import com.youdianstar.app.util.DataAppManager
import com.youdianstar.app.util.WalletDialogUtil
import com.youdianstar.app.common.DataCode
import com.youdianstar.app.common.entity.BusEntity
import com.zhpan.bannerview.constants.PageStyle
import com.youdianstar.app.common.auko.startActivity
import com.youdianstar.app.adapter.CardMethodAdapter
import org.koin.androidx.viewmodel.ext.android.viewModel


/**
 * File: WalletActivity
 * Author: 82149 Create: 2021/11/24 11:37
 * Changes (from 2021/11/24)
 * --------------------------------------------------
 * description:
 * ---------------------------------------------------
 *
 */
class WalletActivity :BaseActivity<ActivityWalletBinding, WalletViewModel>(){
    override fun layoutId(): Int = R.layout.activity_wallet

    override fun initVariableId(): Int = BR.viewModel

    override fun initViewModel(): WalletViewModel {
        val model: WalletViewModel by viewModel()
        return model
    }

    private val mHandler = Handler(Looper.myLooper()!!)
    private val methodList : MutableList<CardEntity> = mutableListOf()
    private var mListAdapter: CardMethodAdapter?=null

    private val bannerDatas: MutableList<CardBanner> = ArrayList()
    private var defaultIndex = 0
    private lateinit var editListener: CardEditListener
    private var cardDialog : Dialog? =null
    private var selectId:Int = 0

    override fun initViewLayout() {
        super.initViewLayout()
        ImmersionBar.with(this)
            .statusBarColor(R.color.black)
            .statusBarDarkFont(true)
            .titleBarMarginTop(mBinding.topHeader)
            .init()
        mBinding.headBack.setThrottleListener {
            finish()
        }

        mBinding.rcyMethod.layoutManager = LinearLayoutManager(this)
        mListAdapter = CardMethodAdapter(this, dataList = methodList)
        mBinding.rcyMethod.adapter = mListAdapter

        mBinding.bannerCards.setPageStyle(PageStyle.MULTI_PAGE_SCALE)
            .setRevealWidth(resources.getDimensionPixelOffset(R.dimen.dp_10),resources.getDimensionPixelOffset(R.dimen.dp_10))
            .setPageMargin(resources.getDimensionPixelOffset(R.dimen.dp_6))
            .setCanLoop(false)
            .setIndicatorVisibility(View.GONE)
            .setLifecycleRegistry(lifecycle)
            .setAdapter(CardBannerAdapter(this,object :CardBannerAdapter.OnItemListener{
                override fun onAddCard() {
                    startActivity<AddCardActivity>()
                }

                override fun onEditCard(position: Int) {
                    bannerDatas[position].card?.let {
                        showRemoveCardNotify(it.id)
                    }
                }
            })).create(bannerDatas)
        mBinding.bannerCards.removeDefaultPageTransformer()

        if (DataAppManager.instance.rentScanTag){
            toastShow(getString(R.string.home_oneOfOptionsToast))
        }

        EventBus.post(BusEntity(DataCode.CLOSE_DRAWER))//关闭侧边栏
    }

    override fun initData() {
        super.initData()
        editListener = CardEditListener()
    }

    override fun onResume() {
        super.onResume()
        selectId = 0
        mViewModel.getWallet(true)
    }

    private fun loadWallet() {
        mHandler.postDelayed({
            mViewModel.getWallet(false)
        }, 300L)
    }

    override fun initLiveObserver() {
        super.initLiveObserver()
        mViewModel.walletLiveData.observe(this, object : BaseApiResultObserver<WalletInfo>(){
            override fun onDataResult(data: WalletInfo?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    mViewModel.walletDataFiled.set(it)
                    setWalletLayout(it)
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })

        mViewModel.defaultLiveData.observe(this, object : BaseApiResultObserver<Any>(true){
            override fun onDataResult(data: Any?) {
                super.onDataResult(data)
                cardDialog?.dismiss()
                editListener.onResetStateLayout()
                loadWallet()
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                editListener.onResetStateLayout()
                editListener.onCardStateDefault(editListener.isCardDefault)
                toastShow(e)
            }
        })

        mViewModel.unBindLiveData.observe(this,object : BaseApiResultObserver<CardUnbindRes>(){
            override fun onDataResult(data: CardUnbindRes?) {
                super.onDataResult(data)
                selectId = 0 //清理选择id
                data?.let {
                    //1：有租借中的订单 2：自己有未支付的订单 3：有调查中的订单4：子账号有未支付订单 5:子账号有调查中的订单 6:子账号有租借中的订单 7:已开通亲情圈
                    when(it.result){
                        0-> loadWallet()
                        1-> {
                            showRefundError(msg = getString(R.string.Dialog_DeleteCard_Message1), confirmAction = {}, isShowLeft = false)
                        }
                        2-> {
                            showRefundError(msg = getString(R.string.Dialog_DeleteCard_Message2), cancelText = getString(R.string.Set_notNow), confirmText = getString(R.string.home_gotoPay),
                                confirmAction = {
                                    //跳转支付
                                    it.order?.let { order->
                                        paymentActionIntent(this@WalletActivity,BisType.Bis_Rent,order.money, orderNo = order.orderNo, orderInfo = order)
                                    }
                                },isShowLeft = true)
                        }
                        3-> {
                            showRefundError(msg = getString(R.string.Dialog_DeleteCard_Message3), confirmAction = {}, isShowLeft = false)
                        }
                    }
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                toastShow(e)
            }
        })

        mViewModel.refundLiveData.observe(this,object : BaseApiResultObserver<CardUnbindRes>(){
            override fun onDataResult(data: CardUnbindRes?) {
                super.onDataResult(data)
                dismissDialog()
                data?.let {
                    //1：有租借中的订单 2：自己有未支付的订单 3：有调查中的订单4：子账号有未支付订单 5:子账号有调查中的订单 6:子账号有租借中的订单 7:已开通亲情圈
                    when(it.result){
                        0-> toRefundResult()
                        1-> {
                            showRefundError(msg = getString(R.string.Dialog_Refund_Message1),confirmAction = {},isShowLeft = false)
                        }
                        2-> {
                            showRefundError(msg = getString(R.string.Dialog_Refund_Message2),cancelText = getString(R.string.Set_notNow), confirmText = getString(R.string.home_gotoPay),
                                confirmAction = {
                                  //跳转支付
                                   it.order?.let { order->
                                       paymentActionIntent(this@WalletActivity,BisType.Bis_Rent,order.money,orderNo = order.orderNo,orderInfo = order)
                                   }
                                },isShowLeft = true)
                        }
                        3-> {
                            showRefundError(msg = getString(R.string.Dialog_Refund_Message3),confirmAction = {},isShowLeft = false)
                        }
                    }
                }
            }

            override fun onNetError(code: Int, e: String?) {
                super.onNetError(code, e)
                dismissDialog()
                toastShow(e)
            }
        })
    }

    override fun initClickEvent() {
        mBinding.tvHistory.setThrottleListener {
            //跳转记录页面
            startActivity<RecordActivity>()
        }

        mBinding.btnTopUp.setThrottleListener {
            mViewModel.walletDataFiled.get()?.let {
                if (it.depositAmount<=0)
                    toTopDeposit(it.deposit)
                else
                    showRefundNotify()
            }
        }

        mBinding.btnAddAction.setThrottleListener {
            //加卡
            startActivity<AddCardActivity>()
        }
    }

    /**
     * 设置钱包数据
     * @param data 钱包数据
     */
    private fun setWalletLayout(data: WalletInfo){
        val symbolStr = DataAppManager.instance.symbolTx()
        if (data.depositAmount>0){
            mBinding.tvDepositAmount.text = symbolStr+MathUtil.round(data.depositAmount)
            mBinding.btnTopUp.text = getString(R.string.wallet_refund)
        } else{
            mBinding.tvDepositAmount.text = "$symbolStr 0.00"
            mBinding.btnTopUp.text = getString(R.string.wallet_addDeposit)
        }
        //卡列表 弃用
//        methodList.clear()
//        mListAdapter?.notifyDataSetChanged()
        //卡Banner
        bannerDatas.clear()
        data.cardList?.let {
            if (it.isNotEmpty()){
                it.forEach { card->
                    bannerDatas.add(CardBanner(2,card))
                    if (selectId!=0 && card.id==selectId){
                        defaultIndex = it.indexOf(card)
                    }
                }
            }else{
                bannerDatas.add(CardBanner(1))
            }
        }
        //刷新 banner数据
        mBinding.bannerCards.refreshData(bannerDatas)
        mBinding.bannerCards.currentItem = defaultIndex
    }

    /**
     * 跳转押金支付
     * @param depositAmount 押金支付金额
     */
    private fun toTopDeposit(depositAmount:Double){
        //startActivity<PaymentCodeActivity>(Extra.IT_TYPE to BisType.Bis_Deposit,Extra.IT_MONEY to depositAmount)
        paymentActionIntent(this, bisType = BisType.Bis_Deposit, amount = depositAmount)
    }

    /**跳转退款结果*/
    private fun toRefundResult(){
        startActivity<RefundStateActivity>()
    }

    /**提现提示*/
    private fun showRefundNotify(){
        WalletDialogUtil.instance.showNotifyDialog(this,
            title =getString(R.string.wallet_refund),
            msg = getString(R.string.Dialog_Refund_Message),
            leftAction = {

            },rightAction = {
                mViewModel.requestRefund()
            },left = getString(R.string.public_notNow),right = getString(R.string.home_confirm))
    }

    /**
     * 提现错误状态提示
     *
     * @param titleText 标题文本
     */
    private fun showRefundError(titleText:String?=null, msg :String, cancelText :String?=null,confirmText :String?=null,
                                confirmAction: (() -> Unit) = { },isShowLeft :Boolean){
        WalletDialogUtil.instance.showNotifyDialog(this,
            title = titleText?:getString(R.string.public_notice), msg = msg,
            leftAction = {

            },left = cancelText?:getString(R.string.public_cancel),
            rightAction = confirmAction, right = confirmText?:getString(R.string.home_confirm),
            isShowLeft = isShowLeft,isShowRight = true)
    }


    /**
     * 删卡提示
     *
     * @param cardId 解绑卡ID
     */
    private fun showRemoveCardNotify(cardId:Int){
        WalletDialogUtil.instance.showNotifyDialog(this,
            title ="",
            msg = getString(R.string.wallet_confirmRmCard),
            leftAction = {

            },rightAction = {
                mViewModel.unBindCard(cardId)
            },left = getString(R.string.wallet_cancel),right = getString(R.string.wallet_remove))
    }

    /**
     * 编辑卡提示(弃用)
     *
     * @param card 卡对象
     */
    private fun showCardEditDialog(card : CardEntity){
        if (null!=cardDialog && cardDialog?.isShowing == true){
            cardDialog?.dismiss()
            cardDialog = null
        }
        editListener.cleanLayout()
        cardDialog = WalletDialogUtil.instance.showEditCardDialog(this,card,editListener)
    }

    inner class CardEditListener : ICardEditListener {
        var vgDeleteConfirm : View? = null
        var ivDeleteRight : ImageView? = null
        var boxDefault :CheckBox? = null

        var isCardDefault = false
        var showConfirm : Boolean = false

        override fun registerLayout(vgConfirm: View, toDelete: ImageView, boxDefault: CheckBox) {
            this.vgDeleteConfirm = vgConfirm
            this.ivDeleteRight = toDelete
            this.boxDefault = boxDefault
            this.showConfirm = false
        }

        override fun cleanLayout() {
            vgDeleteConfirm = null
            ivDeleteRight = null
            boxDefault = null
            showConfirm = false
        }

        override fun onClickDeleteLayout() {
            setConfirmLayout(!showConfirm)
        }

        override fun onDeleteAction(cardId: Int) {
            mViewModel.unBindCard(cardId)
        }

        override fun onCardStateDefault(isDefault: Boolean) {
            isCardDefault = isDefault
            boxDefault?.isChecked = isDefault
        }

        override fun onRequestCardDefault(isDefault: Boolean, cardId: Int) {
            this.boxDefault?.isClickable = false
            mViewModel.setDefaultCard(cardId,isDefault)
        }

        override fun onResetStateLayout() {
            this.boxDefault?.isClickable = true
        }

        private fun setConfirmLayout(isShow :Boolean){
            showConfirm = isShow
            ivDeleteRight?.rotation = if (isShow) 0F else -90F
            vgDeleteConfirm?.visibility = if (isShow) View.VISIBLE else View.GONE
        }
    }

    override fun onDestroy() {
        cardDialog?.dismiss()
        super.onDestroy()
    }

}